package org.mili.ticketeer.ui.priority;

import org.mili.ticketeer.dto.Contact;
import org.mili.ticketeer.dto.Identifieable;
import org.mili.ticketeer.dto.Priority;
import org.mili.ticketeer.service.PriorityService;
import org.mili.ticketeer.service.ServiceException;
import org.mili.ticketeer.service.ServiceFactory;
import org.mili.ticketeer.ui.FormElement;
import org.mili.ticketeer.ui.SimpleForm;
import org.mili.ticketeer.util.Log;

import javax.swing.*;

/**
 * Created with IntelliJ IDEA.
 * User: papa
 * Date: 20.07.13
 * Time: 14:10
 * To change this template use File | Settings | File Templates.
 */
public class PriorityDataForm extends SimpleForm<Priority> {
    private PriorityService priorityService = ServiceFactory.getService(PriorityService.class);

    public PriorityDataForm(String label) {
        super(FormMode.NORMAL, label, new FormElement[]{
                new FormElement(Identifieable.Fields.ID, new JTextField()),
                new FormElement(Priority.Fields.NAME, new JTextField()),
                new FormElement(Priority.Fields.PRIORITY, new JTextField())
        });

        JTextField id = (JTextField) getFormElement(Identifieable.Fields.ID).getComponent();
        id.setEnabled(false);

    }

    @Override
    public void save() throws ServiceException {
        formObject.setName(getString(Priority.Fields.NAME));
        formObject.setPriority(getInt(Priority.Fields.PRIORITY));
        priorityService.write(formObject);
    }

    @Override
    public void reset() {
        if (formObject.getId() > 0) {
            onSelectionChanged(formObject);
        } else {
            onSelectionChanged(new Contact());
        }
    }

    @Override
    public void cancel() {
        reset();
    }

    @Override
    public boolean validation() {
        Log.log(this, "validation", "true");
        return true;
    }

    @Override
    public void onSelectionChanged(Object element) {
        Log.log(this, "selectionChanged", "element: %s", element);
        if (element instanceof Priority) {
            formObject = (Priority) element;
            updateTextField(Identifieable.Fields.ID, String.valueOf(formObject.getId()));
            updateTextField(Priority.Fields.PRIORITY, String.valueOf(formObject.getPriority()));
            updateTextField(Priority.Fields.NAME, formObject.getName());
        }
        Log.log(this, "selectionChanged", "end");
    }

}
